<template>
  <view id="app">
    <view style="margin-bottom: 15px;">
      <text style="font-size: 20px;">登录</text>
    </view>
    <form @submit="onSubmit">
      <view class="van-field">
        <text class="van-field__label">用户名</text>
        <input 
          v-model="username" 
          name="用户名" 
          placeholder="用户名" 
          :data-rules="JSON.stringify([{ required: true, message: '请填写用户名' }])"
        />
      </view>
      <view class="van-field">
        <text class="van-field__label">密码</text>
        <input 
          v-model="password" 
          password 
          name="密码" 
          placeholder="密码" 
          :data-rules="JSON.stringify([{ required: true, message: '请填写密码' }])"
        />
      </view>
      <view style="margin: 16px">
        <button form-type="submit" type="primary" hover-class="button-hover">登录</button>
      </view>
    </form>
  </view>
</template>

<script>
import { Request } from '@/api/index.js';

export default {
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    async onSubmit() {
      const params = {
        username: this.username,
        password: this.password
      };
      try {
        const res = await Request({
          url: '/login',
          method: 'POST',
          data: params
        });
        
        if (res.data.success && res.data.token) {
          uni.setStorageSync('token', res.data.token);
          uni.setStorageSync('username', this.username);
          uni.navigateTo({
            url: '/pages/HomeView/HomeView'
          });
        } else {
          uni.showToast({
            title: res.data.msg || '登录失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '请求出错: ' + error.message,
          icon: 'none'
        });
        console.error('请求出错:', error);
      }
    }
  }
};
</script>

<style scoped>
.van-field {
  margin-bottom: 15px;
}
.van-field__label {
  display: block;
  margin-bottom: 5px;
}
</style>
